/*   
 *   Copyright (C) 2012  Alvin Aditya H,
 *   					 Shanti F,
 *   					 Selviana 
 *   
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *       
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *       
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *    MA 02110-1301, USA.
 */

package com.scy.btsmart.http.httpserver;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.scy.btsmart.conf.ConfParamName;
import com.scy.btsmart.conf.ConfigParamManage;

import android.content.Context;
import android.util.Log;

public class HttpServer extends Thread{
	
	private static final String TAG = "HttpServer";
	public static int mPort = 8080;
	public Context mctx;
	public boolean mRun = false;
	
	public HttpServer(Context context, String threadName){
		this.mctx = context;
		this.setName(threadName);
		
		mPort = ConfigParamManage.getIntValue(ConfParamName.HTTP_PORT, 8080);
	}
	
	@Override
	public void run(){
		super.run();
		ServerSocket server = null;
		Socket soket = null;
		try {
			server = new ServerSocket(mPort);
			server.setReuseAddress(true);
			server.setSoTimeout(5000);
			mRun = true;
			while(mRun){
				try{
					soket = server.accept();
					Log.i(TAG, "client connected!"); 

					HttpThread httpthread = new HttpThread(mctx, soket, "httpthread");
					httpthread.start();
				} catch (InterruptedIOException eiox){	
				} catch (Exception exc){
					Log.i(TAG, exc.getMessage()); 
				}
				
			}	
			server.close();
			
	    } catch (IOException e) {
	    	System.err.println("");
	    	Log.i(TAG, "Exception in Server.java:socket. " + e.getMessage()); 
	    	try{
		    	if(soket != null) soket.close();
		    	server.close();
	    	} catch(Exception ex){
	    		Log.i(TAG, "Exception in Server.java:cannot close socket. " + e.getMessage()); 
	    	}
			
		} 
		
	}

	public void stopServer() {
		mRun = false;
		
	}

}